package base.utils

import java.math.BigDecimal

/**
 * Created by Jack on 2017/10/16.
 */
object ArithUtil {
    private val DEF_DIV_SCALE = 2


    fun add(d1: Double, d2: Double): Double {
        val b1 = BigDecimal(java.lang.Double.toString(d1))
        val b2 = BigDecimal(java.lang.Double.toString(d2))
        return b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_DOWN).toDouble()

    }

    fun sub(d1: Double, d2: Double): Double {
        val b1 = BigDecimal(java.lang.Double.toString(d1))
        val b2 = BigDecimal(java.lang.Double.toString(d2))
        return b1.subtract(b2).setScale(2, BigDecimal.ROUND_HALF_DOWN).toDouble()

    }

    fun mul(d1: Double, d2: Double): Double {
        val b1 = BigDecimal(java.lang.Double.toString(d1))
        val b2 = BigDecimal(java.lang.Double.toString(d2))
        return b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_DOWN).toDouble()

    }

    @JvmOverloads fun div(d1: Double, d2: Double, scale: Int = DEF_DIV_SCALE): Double {

        if (scale < 0) {
            throw IllegalArgumentException("The scale must be a positive integer or zero")
        }

        val b1 = BigDecimal(java.lang.Double.toString(d1))
        val b2 = BigDecimal(java.lang.Double.toString(d2))
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_DOWN).toDouble()

    }
}